package com.example.ai.controller;

import com.example.ai.dto.community.CommunityShareRequest;
import com.example.ai.dto.community.CommunityShareResponse;
import com.example.ai.model.User;
import com.example.ai.repository.UserRepository;
import com.example.ai.service.CommunityService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import lombok.Data;
import lombok.AllArgsConstructor;

@RestController
@RequestMapping("/api/community")
@RequiredArgsConstructor
public class CommunityController {

    private final CommunityService communityService;
    private final UserRepository userRepository;

    @PostMapping("/share")
    public ResponseEntity<CommunityShareResponse> shareWrongQuestion(
            @Valid @RequestBody CommunityShareRequest request) {
        return ResponseEntity.ok(communityService.shareWrongQuestion(request));
    }

    @GetMapping("/shares")
    public ResponseEntity<Page<CommunityShareResponse>> getCommunityShares(Pageable pageable) {
        return ResponseEntity.ok(communityService.getCommunityShares(pageable));
    }

    @PostMapping("/shares/{id}/view")
    public ResponseEntity<Void> incrementViewCount(@PathVariable Long id) {
        communityService.incrementViewCount(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/shares/{id}/like")
    public ResponseEntity<?> toggleLike(@PathVariable Long id) {
        try {
            Long userId = getUserIdFromAuthentication();
            boolean isLiked = communityService.toggleLike(id,userId);
            String message = isLiked ? "点赞成功" : "取消点赞成功";
            return ResponseEntity.ok(new ApiResponse(message));
        } catch (IllegalStateException e) {
            return ResponseEntity.badRequest()
                .body(new ApiResponse(e.getMessage()));
        }
    }

    @GetMapping("/shares/liked")
    public ResponseEntity<Page<CommunityShareResponse>> getLikedShares(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = getUserIdFromAuthentication();
        return ResponseEntity.ok(communityService.getLikedShares(userId, PageRequest.of(page, size)));
    }

    private Long getUserIdFromAuthentication() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
        return user.getId();
    }
}

@Data
@AllArgsConstructor
class ApiResponse {
    private String message;
} 